package com.liuwei.msmall.cart.interceptor;

import com.liuwei.msmall.cart.to.UserInfoTo;
import com.liuwei.msmall.common.constant.AuthServiceConstant;
import com.liuwei.msmall.common.constant.CartConstant;
import com.liuwei.msmall.common.dto.MemberRespDTO;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Classname CartInterceptor
 * @Description TODO
 * @Date 2020/6/28 0:14
 * @Created by 刘
 */
//注册一个自定义的拦截器，实现所有访问购物车服务的请求都添加一个临时用户
//即使没有登录也可以使用购物车功能
public class CartInterceptor implements HandlerInterceptor{

    //使用ThreadLocal将一些数据进行共享，底层就是使用 Map,根据每个线程id作为key，只要是同一个线程则都能访问到threadLocal中的数据
    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();

    //所有方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断用户是否已经登录
        HttpSession session = request.getSession();
        MemberRespDTO member = (MemberRespDTO) session.getAttribute(AuthServiceConstant.LONGIN_USER);
        UserInfoTo userInfoTo = new UserInfoTo();
        if (member!=null){
            //登录过,将用户的id设置进去
            userInfoTo.setUserId(member.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.CART_USER_KEY)){
                    //如果cookie中有，就封装到userInfoTo中
                    userInfoTo.setUserKey(cookie.getValue());
                    //标识为临时用户
                    userInfoTo.setIsTemporaryUser(true);
                }
            }
        }

        //判断cookie中没有时，说明用户没有登录
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            //如果cookie中没有,生成一个随机uuid
            String uuid= UUID.randomUUID().toString().replace("-","");
            userInfoTo.setUserKey(uuid);
        }

        //放在threadlocal中，只要是同一个线程，就都能访问到
        threadLocal.set(userInfoTo);

        //放行所有请求
        return true;
    }

    //所有方法执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //在向浏览器添加cookie时，先判断浏览器是否已经携带
        if (!threadLocal.get().getIsTemporaryUser()){
            //告诉浏览器设置上我们需要带上的cookie
            Cookie cookie = new Cookie(CartConstant.CART_USER_KEY,threadLocal.get().getUserKey());
            //设置cookie信息
            cookie.setDomain("msmall.com");//设置cookie作用域名
            cookie.setMaxAge(CartConstant.CART_USER_TIMEOUT);//设置cookie过期时间
            response.addCookie(cookie);
        }

    }
}
